package com.example.leetdemo.finash;

import java.util.ArrayList;
import java.util.List;

public class Solution54 {

    public List<Integer> spiralOrder(int[][] matrix) {
        int[][] index = new int[][] {
            {0,0}, {0, matrix[0].length - 1},  {matrix.length - 1, matrix[0].length - 1}, {matrix.length - 1, 0}
        };
        List<Integer> list = new ArrayList<>();
        while (index[0][0] <= index[3][0] && index[0][1] <= index[2][1]) {
            for (int i = index[0][0], j = index[0][1]; j <= index[1][1]; j++) {
                list.add(matrix[i][j]);
            }
            for (int i = index[1][0] + 1, j = index[1][1]; i <= index[2][0]; i++) {
                list.add(matrix[i][j]);
            }
            if (index[0][0] < index[3][0]) {
                for (int i = index[2][0], j = index[2][1] - 1; j >= index[3][1]; j--) {
                    list.add(matrix[i][j]);
                }
                if (index[0][0] < index[1][1]) {
                    for (int i = index[3][0] - 1, j = index[3][1]; i > index[0][0]; i--) {
                        list.add(matrix[i][j]);
                    }
                }
            }
            index[0][0]++; index[0][1]++;
            index[1][0]++; index[1][1]--;
            index[2][0]--; index[2][1]--;
            index[3][0]--; index[3][1]++;
        }
        return list;
    }

    public static void main(String[] args) {
        int[][] test = new int[][] {
                {1,2,3},
                {6,7,8},
                {9,10,11}
        };
        Solution54 solution54 = new Solution54();
        List<Integer> re = solution54.spiralOrder(test);
        re.forEach(System.err::println);
        System.err.println("通过");
    }

}
